#include <stdio.h>

#define FILE_NAME "12_test.file"

typedef struct 
{
    int ID;
    char Name[20];
    float Score;
}STUDENT;


int main(int argc, char const *argv[])
{

    FILE *fp = fopen( FILE_NAME, "w+");
    if ( NULL == fp)
    {
        printf("Fail to fopen %s\n", FILE_NAME);
        return -1;
    }
    printf("Success to fopen %s\n", FILE_NAME);

    
    STUDENT stu[2] = {{1,"Zhang", 90.2},{2, "Li", 80.8}};
    size_t ret2 = fwrite(stu, sizeof(STUDENT), 2, fp);
    printf("Write to file %s total %lu items \n", FILE_NAME, ret2 );

    rewind( fp );

    STUDENT stuRead;

    printf("Start Read from file <%s>\n", FILE_NAME );
    while( ( ret2 = fread( &stuRead, sizeof(STUDENT), 1, fp ) ) != 0 )
    {
        printf("ID: %d\tName: %s\tScore: %.1f\t\n", 
            stuRead.ID, stuRead.Name, stuRead.Score );
    }
    if ( ferror( fp ) )
    {
        perror( "Fail to fread");
        return -1;
    }

    return 0;
}

/*
函数 fwrite
函数 fread
    可以操作文本或者二进制文件

注意点:
    打开文件时, 模式为 "w+"
    fwrite之后, 需要rewind把 file position indicator 设置为起始位置, 然后才能读.
*/